import 'package:flutter/material.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

class DataGrid extends StatefulWidget {
  @override
  _DataGridState createState() => _DataGridState();
}

class _DataGridState extends State<DataGrid> {
  List<UserInfo> userInfoList = [];
  late UserInfoDataSource userInfoDataSource;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    userInfoList = _getUserInfoList();
    userInfoDataSource = UserInfoDataSource(userInfoList);
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: SfDataGrid(
      source: userInfoDataSource,
          columns: <GridColumn>[
            GridColumn(columnName: 'id', label: Container(
              padding: EdgeInsets.all(16.0),
              alignment: Alignment.center,
              child: Text('id'),
            )),
            GridColumn(columnName: '昵称', label: Container(
              padding: EdgeInsets.all(16.0),
              alignment: Alignment.center,
              child: Text('nickName'),
            )),
            GridColumn(columnName: '账号', label: Container(
              padding: EdgeInsets.all(16.0),
              alignment: Alignment.center,
              child: Text('userName'),
            )),
          ],
    ));
  }

  List<UserInfo> _getUserInfoList() {
    return [UserInfo(id: "1", nickName: "name1", userName: "admin1")];
  }
}

class UserInfoDataSource extends DataGridSource {
  List<DataGridRow> _userInfoRows = [];

  UserInfoDataSource(List<UserInfo> userInfoList) {
    _userInfoRows = userInfoList
        .map<DataGridRow>((e) => DataGridRow(cells: [
              DataGridCell(columnName: 'id', value: e.id),
              DataGridCell(columnName: 'nickName', value: e.nickName),
              DataGridCell(columnName: 'userName', value: e.userName)
            ]))
        .toList();
  }
  @override
  List<DataGridRow> get rows => _userInfoRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    return DataGridRowAdapter(
        cells: row.getCells().map<Widget>((dataGridCell) {
      return Container(
        alignment: Alignment.center,
        padding: EdgeInsets.all(16.0),
        child: Text(dataGridCell.value.toString()),
      );
    }).toList());
  }
}
